package com.jumi.microservice.service.comment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.ImageResizeEnum;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.ImageResizeUtil;
import com.jumi.microservice.constant.refundgoods.CancelUserFlagEnum;
import com.jumi.microservice.controller.comment.api.SensitiveWordsUtil;
import com.jumi.microservice.domain.GoodsSkuInfoDTO;
import com.jumi.microservice.dto.comment.commentEnum.CommentEnum;
import com.jumi.microservice.dto.comment.dto.*;
import com.jumi.microservice.dto.order.OrderLogRequest;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.dto.reponse.UserExternalResponse;
import com.jumi.microservice.entity.Comment;
import com.jumi.microservice.entity.SpecialKeyword;
import com.jumi.microservice.entity.UserOrder;
import com.jumi.microservice.mapper.CommentMapper;
import com.jumi.microservice.mapper.SpecialKeywordMapper;
import com.jumi.microservice.mapper.UserOrderMapper;
import com.jumi.microservice.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Scw
 * @Date 2020-08-04 17:56
 */
@DubboService(interfaceClass = ICommentService.class)
public class CommentServiceImpl implements ICommentService {

    private static final Logger log = LoggerFactory.getLogger(CommentServiceImpl.class);
    @Resource
    UserOrderMapper userOrderMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private SpecialKeywordMapper specialKeywordMapper;
    /*引入商品接口*/
    @DubboReference
    private CommodityApi goodsClient;

    @DubboReference
    private IUserExternalService iUserExternalService;
    @DubboReference
    private IMemberService iMemberService;

    @Resource
    private IOrderDubboService orderDubboService;

    @Resource
    RedisTemplate<String, String> redisTemplate;

    private static final String newOneComment = "newOneComment::";

    @Override
    public CommentApiOneResponse commentNewOne(Long spuId) {
        CommentApiOneRequest commentApiOneRequest = new CommentApiOneRequest();
        commentApiOneRequest.setSpuGid(spuId.intValue());
        return commentNewOned(commentApiOneRequest);
//        return getCommentNewOned(commentApiOneRequest);
    }

    @Override
    public Boolean addComment(CommentApiAddRequest commentApiAddRequest) {
        //获取当前用户ID
        Long userId = commentApiAddRequest.getUid();
        if (userId == null) {
            throw new BaseException(CommentEnum.NO_LOGIN.getCode(), CommentEnum.NO_LOGIN.getMessage());
        }
        Integer gid = commentApiAddRequest.getGid();
        if (gid == null) {
            throw new BaseException(CommentEnum.COMMENT_GId.getCode(), CommentEnum.COMMENT_GId.getMessage());
        }
        Integer spuGid1 = commentApiAddRequest.getSpuGid();
        if (spuGid1 == null || spuGid1.equals("")) {
            throw new BaseException(CommentEnum.COMMENT_SPUGID.getCode(), CommentEnum.COMMENT_SPUGID.getMessage());
        }
        //查询信息
        String content = commentApiAddRequest.getContent().trim();
        //字数限制
        if (content.length() > 200) {
            throw new BaseException(CommentEnum.COMMENT_LENGTH_LONG.getCode(), CommentEnum.COMMENT_LENGTH_LONG.getMessage());
        }
        if (content == null) {
            commentApiAddRequest.setContent("用户默认好评！");
        }
        commentApiAddRequest.setContent(content);

        String images = commentApiAddRequest.getImages();
        if (images != null) {
            //图片以；分割
            String[] idArr = images.split(";");
            if (idArr.length > 6) {
                throw new BaseException(CommentEnum.COMMENT_IMAGES_LONG.getCode(), CommentEnum.COMMENT_IMAGES_LONG.getMessage());
            }
            if (idArr.length > 0) {
                commentApiAddRequest.setIsImages((byte) 1);
            }
        }
        /*查询spugid  uid是否有数据如果有设置为1 否则为0，并把已有数据更新1*/
        QueryWrapper<Comment> spuWrapper = new QueryWrapper<>();
        spuWrapper.eq("spu_gid", spuGid1);
        spuWrapper.eq("uid", userId);
        Integer commentsList = commentMapper.selectCount(spuWrapper);
        log.info("评论添加查询日志:[{}]", JSON.toJSONString(commentsList));
        if (commentsList > 0) {
            //回头客
            commentApiAddRequest.setIsRepeatCustomers((byte) 1);
            Integer integer = commentMapper.repeatUpdata(spuGid1);
            if (integer == 0) {
                throw new BaseException(CommentEnum.COMMENT_REPEAT_ERROR.getCode(), CommentEnum.COMMENT_REPEAT_ERROR.getMessage());
            }
        }
        //entity
        Comment comments = new Comment();
        BeanUtils.copyProperties(commentApiAddRequest, comments);
        //拼接上uid
        comments.setUid(userId);
        int row = commentMapper.insert(comments);
        if (row > 0) {
            OrderLogRequest request = new OrderLogRequest();
            request.setLog("评价订单");
            UserOrder userOrder = userOrderMapper.selectById(comments.getOrderId());
            request.setOrderSn(userOrder.getOrderNo());
            request.setUserFlag(CancelUserFlagEnum.USER_FLAG_CUSTOMER.getCode().byteValue());
            request.setOperatorId(comments.getUid());
            request.setOperatorName("前端用户");
            orderDubboService.addOrderLog(request);
        }
        return row > 0;
    }

    /**
     * 评论列表
     *
     * @param commentApiListRequest
     * @return
     */
    @Override
    public TableDataInfo<CommentApiListResponse> commentsApiList(CommentApiListRequest commentApiListRequest) {
        //获取当前用户ID
        Long userId = commentApiListRequest.getUid();
        if (userId == null) {
            throw new BaseException(CommentEnum.NO_LOGIN.getCode(), CommentEnum.NO_LOGIN.getMessage());
        }
        /**
         * 敏感词
         */
        QueryWrapper<SpecialKeyword> specialWrapper = new QueryWrapper<>();
        specialWrapper.orderByDesc("id").eq("status",1).eq("is_del",0);
        List<SpecialKeyword> specialKeywords = specialKeywordMapper.selectList(specialWrapper);
        log.debug("评论列表：敏感词:[{}]", JSON.toJSONString(specialKeywords));
        Set<String> sensitiveWordSet = new HashSet<>();
        for (SpecialKeyword specialKeyword : specialKeywords) {
            sensitiveWordSet.add(specialKeyword.getSensitiveWords());
        }
        SensitiveWordsUtil sensitiveWordsUtil = new SensitiveWordsUtil();
        //初始化
        sensitiveWordsUtil.init(sensitiveWordSet);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("uid", userId);
//        queryWrapper.eq("is_hide", 0);
        IPage<Comment> page = new Page<>(commentApiListRequest.getPageNum(), commentApiListRequest.getPageSize());
        page = commentMapper.selectPage(page, queryWrapper);
        log.debug("评论列表：敏感词page:[{}]", JSON.toJSONString(page));
        List<Comment> commentPage = page.getRecords();
        log.debug("评论列表：敏感词commentPage:[{}]", JSON.toJSONString(commentPage));
        if (commentPage.size() == 0) {
            throw new BaseException(CommentEnum.COMMENT_NEW_ONE.getCode(), CommentEnum.COMMENT_NEW_ONE.getMessage());
        }
        //有序列表
        List<CommentApiListResponse> result = new ArrayList<>();

        /* 根据商品ID--sku查询商品主图【商品服务提供接口】，提取商品id，调用商品接口返回商品信息列表*/
        List<Long> skuIds = new ArrayList<>();
        Integer skuUid = null;
        List<GoodsSkuInfoDTO> getGoodsSkuInfoByIds = new ArrayList<>();

        for (Comment comments : commentPage) {
            skuIds.add(comments.getGid().longValue());
            skuUid = comments.getUid().intValue();
        }
        log.debug("评论列表：根据商品ID--sku查询商品主图【商品服务提供接口】skuIds:[{}]", JSON.toJSONString(skuIds));
        if (skuIds != null) {
            getGoodsSkuInfoByIds = goodsClient.getGoodsSkuInfoByIds(skuIds);
            log.debug("评论列表：根据商品ID--sku查询商品主图【商品服务提供接口】:[{}]", JSON.toJSONString(getGoodsSkuInfoByIds));
        }
        //调用用户接口获取用户信息
        String userName = null;
        String userImage = null;
        if (skuUid != null) {
            /*用户的所有信息*/
            UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(skuUid);
            log.debug("评论列表----【用户的所有信息】:[{}]", JSON.toJSONString(userExternalResponse));
            if (userExternalResponse != null) {
                userName = userExternalResponse.getNickName();
                userImage = userExternalResponse.getHeadUrl();
            }
        }


        //在下面方法中直接使用
        for (Comment comments : commentPage) {
            CommentApiListResponse commentApiListResponse = new CommentApiListResponse();
            ///敏感词替换为*
            String filterStr = sensitiveWordsUtil.replaceSensitiveWord(comments.getContent(), '*');
            comments.setContent(filterStr);
            BeanUtils.copyProperties(comments, commentApiListResponse);
            commentApiListResponse.setImages(ImageResizeUtil.batchImageResize(comments.getImages(), ImageResizeEnum.LIST));
            //设置商品名称.图片
            if (getGoodsSkuInfoByIds != null) {
                for (GoodsSkuInfoDTO getGoodsSkuIds : getGoodsSkuInfoByIds) {
                    if (getGoodsSkuIds.getId().equals(comments.getGid().longValue())) {
                        commentApiListResponse.setGidTitle(getGoodsSkuIds.getGoodsName());
                        commentApiListResponse.setGidImages(ImageResizeUtil.imageResize
                                (getGoodsSkuIds.getGoodsImage(), ImageResizeEnum.SMALL));
                    }
                }
            }

            //根据当前用户ID，获取用户相关信息
            commentApiListResponse.setUserName(userName);
            commentApiListResponse.setUserImage(userImage);
            commentApiListResponse.setCommentId(comments.getId());
            result.add(commentApiListResponse);
        }

        TableDataInfo<CommentApiListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;

    }

    /**
     * spu商品 评论列表
     *
     * @param commentSpuRequest
     * @return
     */
    @Override
    public TableDataInfo<CommentApiListResponse> commentListSpuList(CommentSpuRequest commentSpuRequest) {
        Integer spuId = commentSpuRequest.getSpuGid();
        if (spuId == null) {
            throw new BaseException(CommentEnum.COMMENT_GId.getCode(), CommentEnum.COMMENT_GId.getMessage());
        }
        Integer types = commentSpuRequest.getCommentType();
        if (types == null) {
            types = 1;
        }
        /**敏感词*/
        QueryWrapper<SpecialKeyword> specialWrapper = new QueryWrapper<>();
        specialWrapper.orderByDesc("id").eq("status",1).eq("is_del",0);
        List<SpecialKeyword> specialKeywords = specialKeywordMapper.selectList(specialWrapper);
        log.debug("spu商品评论列表----【敏感词】:[{}]", JSON.toJSONString(specialKeywords));
        Set<String> sensitiveWordSet = new HashSet<>();
        for (SpecialKeyword specialKeyword : specialKeywords) {
            sensitiveWordSet.add(specialKeyword.getSensitiveWords());
        }
        SensitiveWordsUtil sensitiveWordsUtil = new SensitiveWordsUtil();
        //初始化
        sensitiveWordsUtil.init(sensitiveWordSet);
        Byte isImages = commentSpuRequest.getIsImages();
        Byte isRepeatCustomers = commentSpuRequest.getIsRepeatCustomers();
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_gid", spuId).eq("is_hide", 0);
        queryWrapper.orderByDesc("id");
        switch (types) {
            case 2:
                queryWrapper.in("product_satisfaction", 4, 5);
                break;
            case 3:
                queryWrapper.in("product_satisfaction", 2, 3);
                break;
            case 4:
                queryWrapper.in("product_satisfaction", 1);
                break;
            default:
                break;
        }
        if (isImages != null && isImages == (byte) 1) {
            queryWrapper.in("is_images", isImages);
        }
        if (isRepeatCustomers != null && isRepeatCustomers == (byte) 1) {
            queryWrapper.in("is_repeat_customers", isRepeatCustomers);
        }
        queryWrapper = getQueryWrapper(queryWrapper, types, isImages == null ? 0 : isImages,
                isRepeatCustomers == null ? 0 : isRepeatCustomers, commentSpuRequest.getUid());
        IPage<Comment> page = new Page<>(commentSpuRequest.getPageNum(), commentSpuRequest.getPageSize());
        page = commentMapper.selectPage(page, queryWrapper);
        List<Comment> commentPage = page.getRecords();
        log.debug("spu商品评论列表----【commentPage】:[{}]", JSON.toJSONString(commentPage));
        if (commentPage.size() == 0) {
            throw new BaseException(CommentEnum.COMMENT_NEW_ONE.getCode(), CommentEnum.COMMENT_NEW_ONE.getMessage());
        }
        //根据用户uid查用户消息【用户服务提供接口】
        List<Integer> skuIds = commentPage.stream().map(c -> c.getUid().intValue()).collect(Collectors.toList());
        ResponseResult<List<JmUserReponse>> memberByUid = null;
        if (!skuIds.isEmpty()) {
            log.debug("spu商品评论列表----【用户id】:[{}]", JSON.toJSONString(skuIds));
            memberByUid = iMemberService.getMemberByUids(skuIds);
            log.debug("spu商品评论列表----【用户memberByUid】:[{}]", JSON.toJSONString(memberByUid));
        }
        Map<Long, JmUserReponse> userMap = memberByUid.getData().stream().collect(Collectors.toMap(u -> u.getId().longValue(), u -> u));
        //有序列表
        List<CommentApiListResponse> result = new ArrayList<>();
        for (Comment comments : commentPage) {
            ///敏感词替换为*
            String filterStr = sensitiveWordsUtil.replaceSensitiveWord(comments.getContent(), '*');
            comments.setContent(filterStr);
            CommentApiListResponse commentApiListResponse = new CommentApiListResponse();
            BeanUtils.copyProperties(comments, commentApiListResponse);
            commentApiListResponse.setImages(ImageResizeUtil.batchImageResize(comments.getImages(), ImageResizeEnum.LIST));
            //根据当前用户ID，获取用户相关信息
            //设置用户信息
            if (userMap.containsKey(comments.getUid())) {
                JmUserReponse jmUserReponse = userMap.get(comments.getUid());
                commentApiListResponse.setUserName(jmUserReponse.getName());
                commentApiListResponse.setUserImage(ImageResizeUtil.imageResize(jmUserReponse.getAvatar(), ImageResizeEnum.SMALL));
                if (comments.getIsAnonymous().equals((byte) 1)) {
                    commentApiListResponse.setUserImage(ImageResizeUtil.imageResize("http://img.jumituangou.com/clientUse/public/defaultimg.png",
                            ImageResizeEnum.SMALL));
                    if(jmUserReponse.getName().length()<=1){
                        commentApiListResponse.setUserName(jmUserReponse.getName().concat("*"));
                    }else{
                        commentApiListResponse.setUserName(jmUserReponse.getName().replaceAll("(?<=\\S)\\S", "*"));
                    }
                }
            }
            commentApiListResponse.setCommentId(comments.getId());
            result.add(commentApiListResponse);
        }
        TableDataInfo<CommentApiListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;
    }

    /**
     * @param queryWrapper
     * @param types
     * @param isImages
     * @param isRepeatCustomers
     * @param uid
     * @return
     */
    QueryWrapper<Comment> getQueryWrapper(QueryWrapper<Comment> queryWrapper, Integer types, Byte isImages, Byte isRepeatCustomers, Long uid) {
        if (types < 2 && isImages == 0 && isRepeatCustomers == 0) {
            queryWrapper.or(qw -> qw.eq("is_hide", 1).eq("uid", uid));
        } else if (types == 2 && isImages == 0 && isRepeatCustomers == 1) {
            queryWrapper.or(qw -> qw.eq("is_hide", 1).in("product_satisfaction", 4, 5)
                    .eq("is_repeat_customers", 1)
                    .eq("uid", uid));
        } else if (types == 2 && isImages == 1 && isRepeatCustomers == 0) {
            queryWrapper.or(qw -> qw.eq("is_hide", 1).in("product_satisfaction", 4, 5)
                    .eq("is_images", 1)
                    .eq("uid", uid));
        } else if (types == 3 && isImages == 1 && isRepeatCustomers == 0) {
            queryWrapper.or(qw -> qw.eq("is_hide", 1).in("product_satisfaction", 2, 3)
                    .eq("is_images", 1)
                    .eq("uid", uid));
        } else if (types == 3 && isImages == 0 && isRepeatCustomers == 1) {
            queryWrapper.or(qw -> qw.eq("is_hide", 1).in("product_satisfaction", 2, 3)
                    .eq("is_repeat_customers", 1)
                    .eq("uid", uid));
        } else if (types == 4 && isImages == 0 && isRepeatCustomers == 1) {
            queryWrapper.or(qw -> qw.eq("is_hide", 1).in("product_satisfaction", 1)
                    .eq("is_repeat_customers", 1)
                    .eq("uid", uid));
        } else if (types == 4 && isImages == 1 && isRepeatCustomers == 0) {
            queryWrapper.or(qw -> qw.eq("is_hide", 1).in("product_satisfaction", 1)
                    .eq("is_images", 1)
                    .eq("uid", uid));
        }
        return queryWrapper;
    }


    /**
     * 商品评论列表orderid
     *
     * @param commentApiUidRequest
     * @return
     */
    @Override
    public TableDataInfo<CommentApiUidResponse> commentListUid(CommentApiUidRequest commentApiUidRequest) {
        Long uid = commentApiUidRequest.getUid();
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        queryWrapper.orderByDesc("id");
        List<Comment> comment = commentMapper.selectList(queryWrapper);
        log.debug("商品评论列表orderid----【comment】:[{}]", JSON.toJSONString(comment));
        if (comment.size() == 0) {
            throw new BaseException(CommentEnum.COMMENT_NEW_ONE.getCode(), CommentEnum.COMMENT_NEW_ONE.getMessage());
        }
        List<CommentApiUidResponse> result = new ArrayList<>();
        for (Comment comment3 : comment) {
            CommentApiUidResponse commentApiUidResponse = new CommentApiUidResponse();
            BeanUtils.copyProperties(comment3, commentApiUidResponse);
            result.add(commentApiUidResponse);
        }
        TableDataInfo<CommentApiUidResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        return dataInfo;
    }

    /**
     * 评论批量添加
     *
     * @param commentApiAddBatchRequest
     * @return
     */
    @Override
    public boolean addBatchComment(CommentApiAddBatchRequest commentApiAddBatchRequest) {
        Long userId = commentApiAddBatchRequest.getUid();
        if (userId == null) {
            throw new BaseException(CommentEnum.NO_LOGIN.getCode(), CommentEnum.NO_LOGIN.getMessage());
        }
        List<Comment> commentList = new ArrayList<>();
        List<Integer> userOrders = new ArrayList<>();
        List<CommentApiGoodsRequest> listArr = commentApiAddBatchRequest.getGoodsList();
        log.debug("评论批量添加----【listArr】:[{}]", JSON.toJSONString(listArr));
        for (CommentApiGoodsRequest commentApiGoodsRequest : listArr) {
            Comment comment = new Comment();
            UserOrder usersOrderId = new UserOrder();
            //条件判断
            Integer gid = commentApiGoodsRequest.getGid();
            if (gid == null) {
                throw new BaseException(CommentEnum.COMMENT_GId.getCode(), CommentEnum.COMMENT_GId.getMessage());
            }
            String content = commentApiGoodsRequest.getContent().trim();
            //字数限制
            if (content.length() > 200) {
                throw new BaseException(CommentEnum.COMMENT_LENGTH_LONG.getCode(), CommentEnum.COMMENT_LENGTH_LONG.getMessage());
            }
            if (content == null || content.equals("")) {
                //评论为空，默认文案并好评
                commentApiGoodsRequest.setContent("用户默认好评！");
            }
            if (commentApiAddBatchRequest.getExpressPackaging() == null) {
                commentApiAddBatchRequest.setExpressPackaging(5);
            }
            if (commentApiAddBatchRequest.getLogisticsServices() == null) {
                commentApiAddBatchRequest.setLogisticsServices(5);
            }
            if (commentApiAddBatchRequest.getServiceAttitude() == null) {
                commentApiAddBatchRequest.setServiceAttitude(5);
            }
            Integer productSatisfaction = commentApiGoodsRequest.getProductSatisfaction();
            if (productSatisfaction == null || productSatisfaction.equals("")) {
                commentApiGoodsRequest.setProductSatisfaction(5);
            }
            Integer spuGid = commentApiGoodsRequest.getSpuGid();
            if (spuGid == null || spuGid.equals("")) {
                throw new BaseException(CommentEnum.COMMENT_SPUGID.getCode(), CommentEnum.COMMENT_SPUGID.getMessage());
            }
            comment.setSpuGid(spuGid);
            String images = commentApiGoodsRequest.getImages();
            if (images != null && !images.equals("")) {
                //图片以；分割
                String[] idArr = images.split(";");
                if (idArr.length > 6) {
                    throw new BaseException(CommentEnum.COMMENT_IMAGES_LONG.getCode(), CommentEnum.COMMENT_IMAGES_LONG.getMessage());
                }
                if (idArr.length > 0) {
                    comment.setIsImages((byte) 1);
                }
            } else {
                comment.setIsImages((byte) 0);
            }
            Integer orderId = commentApiGoodsRequest.getOrderId();
            if (orderId == null) {
                orderId = 0;
            }
            comment.setOrderId(orderId);
            usersOrderId.setId(orderId);
            userOrders.add(usersOrderId.getId());
            /*查询spugid  uid是否有数据如果有设置为1 否则为0，并把已有数据更新1*/
            QueryWrapper<Comment> spuWrapper = new QueryWrapper<>();
            spuWrapper.eq("spu_gid", spuGid);
            spuWrapper.eq("uid", userId);
            spuWrapper.eq("is_hide", 0);
            Integer commentsList = commentMapper.selectCount(spuWrapper);
            log.debug("评论批量添加----【commentsList】:[{}]", JSON.toJSONString(commentsList));
            if (commentsList > 0) {
                //回头客
                comment.setIsRepeatCustomers((byte) 1);
                Integer integer = commentMapper.repeatUpdata(spuGid);
                log.debug("评论批量添加----【integer】:[{}]", JSON.toJSONString(integer));
                if (integer == 0) {
                    throw new BaseException(CommentEnum.COMMENT_REPEAT_ERROR.getCode(), CommentEnum.COMMENT_REPEAT_ERROR.getMessage());
                }
            } else {
                comment.setIsRepeatCustomers((byte) 0);
            }
            Byte isAnonymous = commentApiAddBatchRequest.getIsAnonymous();
            if (isAnonymous == null) {
                isAnonymous = (byte) 0;
            }

            //用户uid
            comment.setUid(commentApiAddBatchRequest.getUid());
            comment.setUserName(commentApiAddBatchRequest.getUserName());
            //商品信息集合
            comment.setGid(commentApiGoodsRequest.getGid());
            comment.setContent(commentApiGoodsRequest.getContent());
            comment.setImages(commentApiGoodsRequest.getImages());
            comment.setProductSatisfaction(commentApiGoodsRequest.getProductSatisfaction());
            //其他共用信息
            comment.setExpressPackaging(commentApiAddBatchRequest.getExpressPackaging());
            comment.setLogisticsServices(commentApiAddBatchRequest.getLogisticsServices());
            comment.setServiceAttitude(commentApiAddBatchRequest.getServiceAttitude());
            comment.setIsAnonymous(isAnonymous);
            commentList.add(comment);
        }
        log.info("评论批量添加----【commentList】:[{}]", JSON.toJSONString(commentList));
        Integer insertComments = commentMapper.batchInsertComment(commentList);
        if (insertComments == 0) {
            throw new BaseException(CommentEnum.COMMENT_INSERT_BATCH_ERROR.getCode(), CommentEnum.COMMENT_INSERT_BATCH_ERROR.getMessage());
        }
        log.debug("评论批量添加----【userOrders】:[{}]", JSON.toJSONString(userOrders));
        String join = StringUtils.join(userOrders, ",");
        log.info("评论批量添加----【join】:[{}]", JSON.toJSONString(join));
        return userOrderMapper.userOrderUpdata(join) > 0;
    }

    /**
     * 最新一条评论
     *
     * @param commentApiOneRequest
     * @return
     */
    public CommentApiOneResponse commentNewOned(CommentApiOneRequest commentApiOneRequest) {
        Integer gId = commentApiOneRequest.getSpuGid();
        if (gId == null) {
            throw new BaseException(CommentEnum.COMMENT_GId.getCode(), CommentEnum.COMMENT_GId.getMessage());
        }
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("is_hide", 0);
        queryWrapper.eq("spu_gid", gId);
        /*取出最新一条数据*/
        List<Comment> commentList = commentMapper.selectList(queryWrapper);
        if (commentList.isEmpty()) {
            redisTemplate.opsForValue().setIfAbsent(newOneComment + gId, JSON.toJSONString(new JSONObject()), 1, TimeUnit.MINUTES);
            throw new BaseException(CommentEnum.COMMENT_NEW_ONE.getCode(), CommentEnum.COMMENT_NEW_ONE.getMessage());
        }
        /**敏感词*/
        QueryWrapper<SpecialKeyword> specialWrapper = new QueryWrapper<>();
        specialWrapper.orderByDesc("id").eq("status",1).eq("is_del",0);
        List<SpecialKeyword> specialKeywords = specialKeywordMapper.selectList(specialWrapper);
        log.debug("spu商品评论列表----【敏感词】:[{}]", JSON.toJSONString(specialKeywords));
        Set<String> sensitiveWordSet = new HashSet<>();
        for (SpecialKeyword specialKeyword : specialKeywords) {
            sensitiveWordSet.add(specialKeyword.getSensitiveWords());
        }
        SensitiveWordsUtil sensitiveWordsUtil = new SensitiveWordsUtil();
        //初始化
        sensitiveWordsUtil.init(sensitiveWordSet);
        //全部数量
        Integer commentAllNum = commentList.size();
        log.debug("最新一条评论----【全部数量】:[{}]", commentAllNum);
        //好评数
        Integer commentHighNum = commentList.stream()
                .filter(c -> c.getProductSatisfaction().equals(4) || c.getProductSatisfaction().equals(5))
                .collect(Collectors.toList()).size();
        log.debug("最新一条评论----【好评数】:[{}]", commentHighNum);

        //好评率
        String highPraiseRate = "0.00%";
        if (commentAllNum != 0 && commentHighNum != 0) {
            //定义格式化起始位数
            String format = "0.00";
            DecimalFormat dec = new DecimalFormat(format);
            highPraiseRate = dec.format((double) commentHighNum / commentAllNum * 100) + "%";
        }
        Comment commentOne = commentList.get(0);
        //用户姓名头像信息
        Integer uid = commentOne.getUid().intValue();
        UserExternalResponse userExternalResponse = new UserExternalResponse();
        if (uid != null && uid != 0) {
            log.debug("最新一条评论----【用户姓名头像信息uid】:[{}]", uid);
            userExternalResponse = iUserExternalService.getUserByUid(uid);
            log.debug("最新一条评论----【用户姓名头像信息】:[{}]", JSON.toJSONString(userExternalResponse));
        }
        //传递信息
        CommentApiOneResponse commentApiOneResponse = new CommentApiOneResponse();
        BeanUtils.copyProperties(commentOne, commentApiOneResponse);
        ///敏感词替换为*
        String filterStr = sensitiveWordsUtil.replaceSensitiveWord(commentOne.getContent(), '*');
        commentApiOneResponse.setContent(filterStr);
        commentApiOneResponse.setImages(ImageResizeUtil.batchImageResize(commentOne.getImages(), ImageResizeEnum.LIST));
        commentApiOneResponse.setCommentAllNum(commentAllNum);
        commentApiOneResponse.setCommentHighNum(highPraiseRate);
        if (userExternalResponse != null) {
            commentApiOneResponse.setUserName(userExternalResponse.getNickName());
            commentApiOneResponse.setUserAvatar(ImageResizeUtil.imageResize(userExternalResponse.getHeadUrl(),
                    ImageResizeEnum.SMALL));
            if (commentOne.getIsAnonymous().equals((byte) 1)) {
                commentApiOneResponse.setUserAvatar(ImageResizeUtil.imageResize("http://img.jumituangou.com/clientUse/public/defaultimg.png",
                        ImageResizeEnum.SMALL));
                if(userExternalResponse.getNickName().length()<=1){
                    commentApiOneResponse.setUserName(userExternalResponse.getNickName().concat("*"));
                }else{
                    commentApiOneResponse.setUserName(userExternalResponse.getNickName().replaceAll("(?<=\\S)\\S", "*"));
                }
            }
        }
        commentApiOneResponse.setUid(commentOne.getUid());
        commentApiOneResponse.setCreateTime(commentOne.getCreateTime());
        //缓存redis
        redisTemplate.opsForValue().set(newOneComment + commentApiOneResponse.getSpuGid(),
                JSON.toJSONString(commentApiOneResponse));
        return commentApiOneResponse;
    }

    /**
     * 新版获取最新一条评论
     *
     * @param commentApiOneRequest
     * @return
     */
    @Override
    public CommentApiOneResponse getCommentNewOned(CommentApiOneRequest commentApiOneRequest) {
        return commentNewOned(commentApiOneRequest);
    }

    /**
     * 定时缓存最新一条评论任务
     */
    @Scheduled(fixedDelay = 10 * 60 * 1000)
    public void schedulerCommentNewOned() {
        log.debug("定时缓存最新一条评论任务->进入");
        QueryWrapper<Comment> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_hide", 0);
        queryWrapper.orderByDesc("id");
        List<Comment> commentList = commentMapper.selectList(queryWrapper);
        if (commentList.isEmpty()) {
            return;
        }
        /**敏感词*/
        QueryWrapper<SpecialKeyword> specialWrapper = new QueryWrapper<>();
        specialWrapper.orderByDesc("id").eq("status",1).eq("is_del",0);
        List<SpecialKeyword> specialKeywords = specialKeywordMapper.selectList(specialWrapper);
        log.debug("spu商品评论列表----【敏感词】:[{}]", JSON.toJSONString(specialKeywords));
        Set<String> sensitiveWordSet = new HashSet<>();
        for (SpecialKeyword specialKeyword : specialKeywords) {
            sensitiveWordSet.add(specialKeyword.getSensitiveWords());
        }
        SensitiveWordsUtil sensitiveWordsUtil = new SensitiveWordsUtil();
        //初始化
        sensitiveWordsUtil.init(sensitiveWordSet);
        Set<Integer> set = commentList.stream().map(Comment::getSpuGid).collect(Collectors.toSet());
        log.debug("查询出的所有SpuId [{}]", JSON.toJSONString(set));
        for (Integer spuGid : set) {
            //全部数量
            List<Comment> list = commentList.stream().filter(c -> c.getSpuGid().equals(spuGid)).sorted(Comparator.comparing(Comment::getId).reversed()).collect(Collectors.toList());
            Integer commentAllNum = list.size();
            if (commentAllNum == 0) {
                continue;
            }
            //好评数
            Integer commentHighNum = list.stream()
                    .filter(c -> c.getProductSatisfaction().equals(4) || c.getProductSatisfaction().equals(5))
                    .collect(Collectors.toList()).size();
            //好评率
            String highPraiseRate = "0.00%";
            if (commentAllNum != 0 && commentHighNum != 0) {
                //定义格式化起始位数
                String format = "0.00";
                DecimalFormat dec = new DecimalFormat(format);
                highPraiseRate = dec.format((double) commentHighNum / commentAllNum * 100) + "%";
            }
            Comment comment = list.get(0);
            //用户姓名头像信息
            Integer uid = comment.getUid().intValue();
            UserExternalResponse userExternalResponse = null;
            if (uid != null && uid != 0) {
                userExternalResponse = iUserExternalService.getUserByUid(uid);
            }
            //传递信息
            CommentApiOneResponse commentApiOneResponse = new CommentApiOneResponse();
            BeanUtils.copyProperties(comment, commentApiOneResponse);
            ///敏感词替换为*
            String filterStr = sensitiveWordsUtil.replaceSensitiveWord(comment.getContent(), '*');
            commentApiOneResponse.setContent(filterStr);
            commentApiOneResponse.setImages(ImageResizeUtil.batchImageResize(comment.getImages(), ImageResizeEnum.LIST));
            commentApiOneResponse.setCommentAllNum(commentAllNum);
            commentApiOneResponse.setCommentHighNum(highPraiseRate);
            if (userExternalResponse != null) {
                commentApiOneResponse.setUserName(userExternalResponse.getNickName());
                commentApiOneResponse.setUserAvatar(ImageResizeUtil.imageResize(userExternalResponse.getHeadUrl(),
                        ImageResizeEnum.SMALL));
                if (comment.getIsAnonymous().equals((byte) 1)) {
                    commentApiOneResponse.setUserAvatar(ImageResizeUtil.imageResize("http://img.jumituangou.com/clientUse/public/defaultimg.png",
                            ImageResizeEnum.SMALL));
                    if(userExternalResponse.getNickName().length()<=1){
                        commentApiOneResponse.setUserName(userExternalResponse.getNickName().concat("*"));
                    }else{
                        commentApiOneResponse.setUserName(userExternalResponse.getNickName().replaceAll("(?<=\\S)\\S", "*"));
                    }
                }
            }
            commentApiOneResponse.setUid(comment.getUid());
            commentApiOneResponse.setCreateTime(comment.getCreateTime());
            redisTemplate.opsForValue().set(newOneComment + comment.getSpuGid(),
                    JSON.toJSONString(commentApiOneResponse));
            log.debug("最新一条评论数据[{}]", JSON.toJSONString(commentApiOneResponse));
        }
        log.debug("定时缓存最新一条评论任务->结束");
    }


    /**
     * spu商品所有评价顶部评论数量一级搜索
     *
     * @param commentSpuGidRequest
     * @return
     */
    @Override
    public CommentSpuGidResponse commentGidNum(CommentSpuGidRequest commentSpuGidRequest) {
        Integer spuGid = commentSpuGidRequest.getSpuGid();
        if (spuGid == null) {
            throw new BaseException(CommentEnum.COMMENT_GId.getCode(), CommentEnum.COMMENT_GId.getMessage());
        }
        CommentSpuGidResponse commentSpuGidResponse = new CommentSpuGidResponse();
        //全部数量
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_gid", spuGid);
        queryWrapper.eq("is_hide", 0);
        List<Comment> commentList = commentMapper.selectList(queryWrapper);
        Integer commentAllNum = commentList.size();
        log.debug("spu商品所有评价顶部评论数量一级搜索----【全部数量】:[{}]", commentAllNum);
        commentSpuGidResponse.setAllNum(commentAllNum);
        //好评数
        Integer commentHighNum = commentList.stream()
                .filter(c -> c.getProductSatisfaction() == 4 || c.getProductSatisfaction() == 5).collect(Collectors.toList()).size();
        log.debug("spu商品所有评价顶部评论数量一级搜索----【好评数】:[{}]", commentHighNum);
        commentSpuGidResponse.setPraiseNum(commentHighNum);
        //中评数
        Integer commentAverageNum = commentList.stream()
                .filter(c -> c.getProductSatisfaction() == 2 || c.getProductSatisfaction() == 3).collect(Collectors.toList()).size();
        log.debug("spu商品所有评价顶部评论数量一级搜索----【中评数】:[{}]", commentAverageNum);
        commentSpuGidResponse.setAverageNum(commentAverageNum);
        //差评数
        Integer commentNegativeNum = commentList.stream()
                .filter(c -> c.getProductSatisfaction() == 1).collect(Collectors.toList()).size();
        log.debug("spu商品所有评价顶部评论数量一级搜索----【查评数】:[{}]", commentNegativeNum);
        commentSpuGidResponse.setNegativeNum(commentNegativeNum);

        //满意度
        //好评率
        String highPraiseRate = "0.00%";
        Integer satisfaction = 0;
        if (commentAllNum != 0 && commentHighNum != 0) {
            //定义格式化起始位数
            String format = "0.00";
            DecimalFormat dec = new DecimalFormat(format);
            double rate = (double) commentHighNum / commentAllNum * 100;
            if (rate <= 20) {
                satisfaction = 1;
            } else if (rate <= 40 && rate > 20) {
                satisfaction = 2;
            } else if (rate <= 60 && rate > 40) {
                satisfaction = 3;
            } else if (rate <= 80 && rate > 60) {
                satisfaction = 4;
            } else {
                satisfaction = 5;
            }
            highPraiseRate = dec.format(rate) + "%";
        }
        commentSpuGidResponse.setSatisfaction(satisfaction);
        commentSpuGidResponse.setHighPraiseRate(highPraiseRate);

        return commentSpuGidResponse;

    }

    /**
     * spu商品所有评价顶部评论数量
     * 二级搜索商品评价图片回头客数量
     *
     * @param commentSpuImageNumRequest
     * @return
     */
    @Override
    public CommentSpuImageNumResponse commentGidTwoNum(CommentSpuImageNumRequest commentSpuImageNumRequest) {
        Integer spuGid = commentSpuImageNumRequest.getSpuGid();
        if (spuGid == null) {
            throw new BaseException(CommentEnum.COMMENT_GId.getCode(), CommentEnum.COMMENT_GId.getMessage());
        }
        Integer commentType = commentSpuImageNumRequest.getCommentType();
        if (commentType == null || commentType.equals("")) {
            throw new BaseException(CommentEnum.COMMENT_SEARCH_TYPE.getCode(), CommentEnum.COMMENT_SEARCH_TYPE.getMessage());
        }
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_gid", spuGid).eq("is_hide", 0);
        List<Integer> satisVals = new ArrayList<Integer>();
        switch (commentType) {
            case 2:
                satisVals.add(4);
                satisVals.add(5);
                queryWrapper.in("product_satisfaction", satisVals);
                break;
            case 3:
                satisVals.add(2);
                satisVals.add(3);
                queryWrapper.in("product_satisfaction", satisVals);
                break;
            case 4:
                satisVals.add(1);
                queryWrapper.in("product_satisfaction", satisVals);
                break;
            default:
                break;
        }
        List<Comment> commentList = commentMapper.selectList(queryWrapper);
        CommentSpuImageNumResponse commentSpuImageNumResponse = new CommentSpuImageNumResponse();
        commentSpuImageNumResponse.setAllNum(commentList.size());
        commentSpuImageNumResponse.setIsImagesNum(commentList.stream().filter(c -> c.getIsImages().equals((byte) 1))
                .collect(Collectors.toList()).size());
        commentSpuImageNumResponse.setIsRepeatCustomersNum(commentList.stream().filter(c -> c.getIsRepeatCustomers().equals((byte) 1))
                .collect(Collectors.toList()).size());
        commentSpuImageNumResponse.setCommentType(commentType);
        commentSpuImageNumResponse.setSpuGid(spuGid);
        return commentSpuImageNumResponse;
    }

    /*全部的数量*/
//    private Integer allNum(Map<String, Integer> map) {
//        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("spu_gid", map.get("spuGid"));
//        List<Integer> satisVals = new ArrayList<Integer>();
//
//        switch (map.get("commentType")) {
//            case 2:
//                satisVals.add(4);
//                satisVals.add(5);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            case 3:
//                satisVals.add(2);
//                satisVals.add(3);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            case 4:
//                satisVals.add(1);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            default:
//                break;
//        }
//        queryWrapper.eq("is_hide", 0);
//        Integer commentAllNum = commentMapper.selectCount(queryWrapper);
//        log.debug("全部的数量:[{}]", JSON.toJSONString(commentAllNum));
//        if (commentAllNum == null) {
//            commentAllNum = 0;
//        }
//        return commentAllNum;
//    }

    /**
     * 有图片的数量
     *
     * @param map
     * @return
     */
//    private Integer imageNum(Map<String, Integer> map) {
//        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("spu_gid", map.get("spuGid"));
//        List<Integer> satisVals = new ArrayList<Integer>();
//
//        switch (map.get("commentType")) {
//            case 2:
//                satisVals.add(4);
//                satisVals.add(5);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            case 3:
//                satisVals.add(2);
//                satisVals.add(3);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            case 4:
//                satisVals.add(1);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            default:
//                break;
//        }
//        queryWrapper.in("is_images", 1);
//        queryWrapper.eq("is_hide", 0);
//        Integer commentAllNum = commentMapper.selectCount(queryWrapper);
//        log.debug("有图片的数量:[{}]", JSON.toJSONString(commentAllNum));
//        if (commentAllNum == null) {
//            commentAllNum = 0;
//        }
//        return commentAllNum;
//    }

    /**
     * 回头客的数量
     *
     * @param map
     * @return
     */
//    private Integer isRepeatNum(Map<String, Integer> map) {
//        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("spu_gid", map.get("spuGid"));
//        List<Integer> satisVals = new ArrayList<Integer>();
//
//        switch (map.get("commentType")) {
//            case 2:
//                satisVals.add(4);
//                satisVals.add(5);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            case 3:
//                satisVals.add(2);
//                satisVals.add(3);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            case 4:
//                satisVals.add(1);
//                queryWrapper.in("product_satisfaction", satisVals);
//                break;
//            default:
//                break;
//        }
//        queryWrapper.eq("is_repeat_customers", 1);
//        queryWrapper.eq("is_hide", 0);
//        Integer count  = commentMapper.selectCount(queryWrapper);
//        log.debug("回头客的数量:[{}]", count);
//        return count;
//    }
}
